package be.android.forap;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.Toast;

import be.android.forap.crypto.AesOcb;
import be.android.forap.crypto.KeyUtil;
import be.android.forap.crypto.PGPEncryption;
import be.android.forap.crypto.PatternUtil;
import be.android.forap.gui.MainActivity;
import be.android.forap.network.DropboxUtil;

public class UserSyncTask  extends AsyncTask<Void, Void, Boolean> {

	private static final String TAG = "UserSyncTask";

	private Activity mActivity;
	private ProgressDialog mDialog;
	private String mUserName;
	private String mPassword;
	private boolean mCanceled;

	public UserSyncTask(Activity activity, String user, String pass) {
		mActivity = activity;

		mUserName = user;
		mPassword = pass;
		mDialog = new ProgressDialog(mActivity);
		mDialog.setMessage("Checking account information in dropbox");
		mDialog.setButton("Cancel", new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				mCanceled = true;
			}
		});

		mDialog.show();
	}

	@Override
	protected Boolean doInBackground(Void... params) {
		try {
			if (mCanceled) {
				return false;
			}

			byte[] dl_secret_encrypted = DropboxUtil.downloadFile(Constants.CONFIG_FILE_NAME);
			byte[] dl_nonce = DropboxUtil.downloadFile(Constants.NONCE_FILE);
			byte[] dl_tag = DropboxUtil.downloadFile(Constants.TAG_FILE);
			Log.e(TAG,"t: "+dl_tag.length);

			/*String[] splitted_dl = dl_secret_encrypted.split("----");


				Log.e(TAG, "SPLIT LENGHT OK" + splitted_dl.length);

			byte[] nonce = new byte[16];
	        byte[] tag = new byte[16];
	        byte[] cyperText;

	        nonce = splitted_dl[0].getBytes();
	        tag = splitted_dl[1].getBytes();
	        cyperText = splitted_dl[2].getBytes();
	        Log.e(TAG,"n: "+nonce.length);
	        Log.e(TAG,"t: "+tag.length);

	        Log.e(TAG,"c: "+cyperText.length);*/
			byte[] dl_salt = DropboxUtil.downloadFile( Constants.SALT_FILE);

			AesOcb engine = new AesOcb();
			byte[] key = KeyUtil.generatePBEKeyWithGivenSalt(mPassword.toCharArray(),dl_salt);
			engine.init(key, 128);
			Log.e(TAG,"key made" + key);
			byte[] decrypted = engine.decrypt(dl_secret_encrypted, dl_secret_encrypted.length, dl_nonce, dl_tag);

			String dl_secret = new String(decrypted);
			//Log.e(TAG,"decrypted " + dl_secret);

			if(!(PatternUtil.matchPGPBlock(dl_secret,PatternUtil.PGP_PRIVATE_KEY))){
				return false;
			}

			byte[] dl_public = DropboxUtil.downloadFile(Constants.PUBLICKEY_FILE_NAME);

			if(!(PatternUtil.matchPGPBlock(new String(dl_public), PatternUtil.PGP_PUBLIC_KEY))){
				return false;
			}
			Log.e(TAG,"Start");
			String pubId = PGPEncryption.readPublicKeyId(dl_public);
			String secId = PGPEncryption.readSecretKeyId(decrypted);
			Log.e(TAG,"p "+ pubId + " " + secId);
			if(!(pubId.equals(secId))){
				return false;
			}
			if(secId.equals(mUserName)){
				ForAp.getInstance().createAccount(mUserName, mPassword, new String(dl_public), dl_secret);			
				return true;
			}
			return false;
		} catch (Exception e) {
			Log.e(TAG,e.toString());
			return false;
		}
	}

	@Override
	protected void onPostExecute(Boolean result) {
		// Our task is complete, so clear it out
		// Hide the progress dialog
		mDialog.dismiss();
		if (result) {
			final Account account = new Account(mUserName, Constants.ACCOUNT_TYPE);
			AccountManager am = AccountManager.get(mActivity);
			// Set contacts sync for this account.
			ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 1);
			ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, true);

			am.addAccountExplicitly(account, mPassword, null);

			Intent i = new Intent(mActivity, MainActivity.class);
			mActivity.startActivity(i);
			mActivity.finish();
			//((Activity) mContext).finish();

		} else {
			showToast("ERROR authentification process");
		}
	}

	private void showToast(String msg) {
		Toast error = Toast.makeText(mActivity, msg, Toast.LENGTH_LONG);
		error.show();
	}


}